<?php
namespace api\user\controller;

use api\user\model\UserBalanceLogModel;
use api\user\model\UserModel;
use api\common\controller\RestUserBaseController;
use api\user\model\ConfigModel;
use think\Db;
use think\Validate;

class BalanceController extends RestUserBaseController
{
    /**
     * 余额变更
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $userId = $this->getUserId();
        $param = $this->request->param();
        $map['where'] = [
            'user_id'=>$userId,
        ];
        $balanceModel = new UserBalanceLogModel();
        $map['order']           = '-createtime';
        if (!empty($param['page'])) {
            $map['page'] = $param['page'];
        }
        if (!empty($param['log_type'])) {
            $map['where']['log_type'] = $param['log_type'];
            $about = 0;
            $mq_to_mu = ConfigModel::getConfig('trade','mq_to_mu');
            $mq_to_mu_value  = $mq_to_mu['value']>0?$mq_to_mu['value']:100;
            //资产类型:1=充值MU,2=活动MU,3=MQ
            switch ($param['log_type']) {
                case '1':
                    $amount = $this->user['pay_mu'];
                    $about = round($this->user['pay_mu'],2);
                    break;
                case '2':
                    $amount = $this->user['active_mu'];
                    $about = round($this->user['active_mu'],2);
                    break;
                case '3':
                    $amount = $this->user['mq'];
                    $about = round($amount*$mq_to_mu_value,2);
                    break;
                default:
                    break;
            }
        }else{
            $this->error('选择钱包类型');
        }
        if (!empty($param['type'])) {
            $map['where']['type'] = $param['type'];
        }
        if (!empty($param['source'])) {
            $map['where']['source'] = $param['source'];
        }
        $data = $balanceModel->getDatas($map);

        $this->success('请求成功', ['amount'=>$amount,'about'=>$about,'list'=> $data]);
            
    }

    /**
     * 转账
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function transfer()
    {
        $userId        = $this->getUserId();
        $param         = $this->request->param();
        $verify_switch = getconfig('verify_switch');
        if($verify_switch>0){
          if(empty($this->user['verify_status'])){
            $this->error(['code' => 10052, 'msg' => '请先完成实名认证']);
            }  
        }
        $validate = new Validate([
            'amount'       =>'require|number|gt:0',
            'mobile'       =>'require',
            'type'         =>'require',
            'pay_password' =>'require',
        ]);
        $validate->message([
            'amount.require'       =>'请输入转账数量',
            'amount.number'        =>'请输入有效转账数量',
            'amount.gt'            =>'请输入正确的转账数量',
            'type.require'         =>'请选择资产类型',
            'mobile.require'       =>'请输入收款人手机',
            'pay_password.require' =>'请输入支付密码',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        
        if (empty($this->user['pay_password'])) {
            $this->error(['code' => 10051, 'msg' => '请先设置支付密码']);
        }
        if ($this->user['pay_password'] != getEncryptPassword($param['pay_password'], $this->user['pay_salt'])) {
            $this->error('支付密码错误');
        }
        
        $file = fopen("../lock/transferlock.txt", "r");
        if (flock($file, LOCK_EX)) {
            // 启动事务
            Db::startTrans();
            $findToUser = Db::name('user')->where('mobile', $param['mobile'])->find();
            
            if (empty($findToUser)) {
                $this->error('收款人不存在');
            }

            if($findToUser['id'] == $userId){
                $this->error('不能转给自己');
            }

            $userInfo = Db::name('user')->where('id', $userId)->lock(true)->find();

            
            if ($userInfo['pay_password'] != getEncryptPassword($param['pay_password'], $userInfo['pay_salt'])) {
                $this->error("支付密码不正确");
            }
            $type = $param['type'];
            $wallet = $arrayName = array('1' =>'pay_mu','2' =>'active_mu','3' =>'mq' );
            if(!isset($wallet[$type])){
                $this->error('钱包类型错误');
            }
            $wallet_field = $wallet[$type];
            $amount = $param['amount'];
            if($userInfo[$wallet_field]<$param['amount']){
                $this->error('资产不足');
            }
            try {
                
                Db::name('user_balance_log')->insert([
                    'user_id' => $userId,
                    'to_user_id' => $findToUser['id'],
                    'createtime' => time(),
                    'amount' => $amount,
                    'admin_remark' => '',
                    'remark' => '转账',
                    'before' => $userInfo[$wallet_field],
                    'after' => $userInfo[$wallet_field] - $amount,
                    'type' => 0,
                    'log_type' => $type,
                    'source' => 11
                ]);
                Db::name('user')->where('id', $userId)->setDec($wallet_field, $amount);

                Db::name('user_balance_log')->insert([
                    'user_id' => $findToUser['id'],
                    'to_user_id' => $userId,
                    'createtime' => time(),
                    'amount' => $amount,
                    'admin_remark' => '',
                    'remark' => '收款',
                    'before' => $findToUser[$wallet_field],
                    'after' => $findToUser[$wallet_field] + $amount,
                    'type' => 1,
                    'log_type' => $type,
                    'source' => 11
                ]);
                Db::name('user')->where('id', $findToUser['id'])->setInc($wallet_field, $amount);
                Db::commit();
                $this->success('转账成功');
            } catch (\think\Exception\DbException $exception) {
                Db::rollback();
                //$this->error($exception->getMessage());
                $this->error('转账失败');
            }
            
            flock($file, LOCK_UN);
        }
        fclose($file);
    }

}